from datetime import datetime

from sqlalchemy import desc
from sqlalchemy_serializer import SerializerMixin

from app import dBSession
from app.Models.BaseModel import BaseModel
from app.Models.Model import VehiclePart
from app.Vendor.Decorator import classTransaction


class VehicleParts(VehiclePart, BaseModel, SerializerMixin):

    @classTransaction
    def get_one(self, vehicle_part):
        res = dBSession.query(VehiclePart).filter(VehiclePart.id == vehicle_part.id).first()
        if not res:
            return None
        res = res.to_dict()
        return res

    @classTransaction
    def get_last_by_vehicle_part(self, vehicle_part):
        res = dBSession.query(VehiclePart).filter(VehiclePart.vehicle_part == vehicle_part).order_by(desc(VehiclePart.id)).first()
        return res

    # 增加
    @classTransaction
    def add(self, vehicle_part):
        vehicle_part.created_at = datetime.now()
        dBSession.add(vehicle_part)
        dBSession.flush()
        return vehicle_part.id

    @classTransaction
    def edit(self, vehicle_part):
        update_data = {"updated_by": vehicle_part.updated_by, "updated_at": datetime.now()}
        if vehicle_part.vehicle_part:
            update_data["vehicle_part"] = vehicle_part.vehicle_part
        dBSession.query(VehiclePart).filter(VehiclePart.id == vehicle_part.id) \
            .update(update_data, synchronize_session=False)
        return True

    # 根据id删除
    @classTransaction
    def delete_by_id(self, vehicle_part):
        update_data = {"updated_by": vehicle_part.updated_by, "updated_at": datetime.now(), "is_delete": 1}
        dBSession.query(VehiclePart).filter(VehiclePart.id == vehicle_part.id).update(update_data)
        return True

    @classTransaction
    def get_list(self, filters: set, offset: int = 0, limit: int = 15):
        res = {}
        res['page'] = {}
        res['page']['count'] = dBSession.query(VehiclePart).filter(*filters).count()
        res['list'] = []
        res['page']['total_page'] = self.get_page_number(res['page']['count'], limit)
        res['page']['current_page'] = offset
        if offset != 0:
            offset = (offset - 1) * limit
        if res['page']['count'] > 0:
            res['list'] = dBSession.query(VehiclePart).filter(*filters).offset(offset).limit(limit).all()
            res['list'] = [c.to_dict() for c in res['list']]
        return res

    @classTransaction
    def get_all(self):
        vehicle_list = dBSession.query(VehiclePart).filter(VehiclePart.is_delete == 0).all()
        vehicle_list = [c.to_dict() for c in vehicle_list]
        return vehicle_list
